#ifndef MONITOR_NEW_EXECUTOR_SYSTEM_TOOL_EXECUTOR_H_
#define MONITOR_NEW_EXECUTOR_SYSTEM_TOOL_EXECUTOR_H_

#include <atomic>
#include <future>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <thread>

// 添加必要的包含
#include "build/proto_src/config.pb.h"
#include "build/proto_src/system_info.pb.h"
#include "core/monitor_queue.h"
#include "parser/system_tool_parser.h"

namespace sysinfo {
namespace monitor {

// 命令执行信息结构体
struct CommandExecutionInfo {
  std::string name;
  std::string path;
  std::string args;
  std::string program;
  std::vector<std::string> parsed_args;
  bool is_oneshot = false;
  bool need_publish = true;
  // 移除interval字段，因为命令进程会持续运行

  // 从配置创建执行信息
  static CommandExecutionInfo FromConfig(const CommandConfig& config);
  
  // 获取完整命令行
  std::string GetFullCommand() const;
  
  // 用于map的比较函数
  bool operator<(const CommandExecutionInfo& other) const {
    return name < other.name || 
           (name == other.name && program < other.program) ||
           (name == other.name && program == other.program && args < other.args);
  }
  
  // 用于unordered_map的相等比较和哈希函数
  bool operator==(const CommandExecutionInfo& other) const {
    return name == other.name && program == other.program && args == other.args;
  }
};

// 执行结果结构体
struct ExecutionResult {
  bool success = false;
  std::string output;
  std::string error_message;
  int exit_code = -1;
};

// 子进程信息结构体
struct SubProcessInfo {
  pid_t pid = -1;
  std::string name;
};

using CommandConfigs = google::protobuf::RepeatedPtrField<CommandConfig>;

class SystemToolExecutor {
 public:
  // 与老项目保持一致，明确区分有界队列和循环队列参数类型
  explicit SystemToolExecutor(const CommandConfigs& command_configs,
                              BoundedMonitorQueue<SystemInfoProto>& system_info_queue,
                              CircularMonitorQueue<SystemInfoProto>& system_info_circular_queue);

  virtual ~SystemToolExecutor();

  // 禁用拷贝和移动
  SystemToolExecutor(const SystemToolExecutor&) = delete;
  SystemToolExecutor& operator=(const SystemToolExecutor&) = delete;

  /**
   * @brief 初始化命令工具
   */
  void Init();

  /**
   * @brief 启动持续监控的命令行工具
   */
  void Start();

  /**
   * @brief 终止所有运行中的工具
   */
  void Stop();

  /**
   * @brief 执行一次性命令行工具
   */
  void StartOnce();

 private:
  // 进程管理
  void TerminateAllProcesses();
  void CheckAndKillExistingProcess(const CommandExecutionInfo& exec_info);

  // 持续命令相关
  void StartContinuousCommand(const CommandExecutionInfo& exec_info);
  void RunContinuousProcess(const CommandExecutionInfo& exec_info);

  // 一次性命令相关
  void ExecuteOneshotCommand(const CommandExecutionInfo& exec_info);
  ExecutionResult ExecuteSync(const CommandExecutionInfo& exec_info) const;

  // 解析相关
  void ParseOneshotOutput(const CommandExecutionInfo& exec_info, const std::string& output);
  void ParseContinuousOutput(const CommandExecutionInfo& exec_info, const std::string& output);

  // 配置验证和转换
  bool ValidateCommand(const CommandExecutionInfo& exec_info) const;
  std::vector<CommandExecutionInfo> ConvertConfigsToExecutionInfo(
      const CommandConfigs& configs) const;

 private:
  // 配置和队列
  CommandConfigs command_configs_;
  std::vector<CommandExecutionInfo> continuous_execution_infos_;
  std::vector<CommandExecutionInfo> oneshot_execution_infos_;

  // 队列引用
  BoundedMonitorQueue<SystemInfoProto>& system_info_queue_;
  CircularMonitorQueue<SystemInfoProto>& system_info_circular_queue_;

  // 线程管理
  std::vector<std::thread> worker_threads_;
  std::atomic<bool> run_ctrl_{false};
  std::atomic<bool> non_reentrant_stop_{false};  // 防止多次析构的标志

  // 管理子进程生命周期的核心结构体
  struct SubProcess {
    pid_t pid = -1;
    std::string name;
  };

  // 锁保护子进程管理结构
  mutable std::mutex subprocess_mutex_;
  // 子进程管理表，使用 CommandExecutionInfo 作为 key
  mutable std::map<CommandExecutionInfo, SubProcess> sub_processes_;

  // 解析器
  std::unique_ptr<SystemToolParser> parser_;
};

}  // namespace monitor
}  // namespace sysinfo

#endif  // MONITOR_NEW_EXECUTOR_SYSTEM_TOOL_EXECUTOR_H_